package com.example.roam.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.ParcelUuid;

import org.jetbrains.annotations.NotNull;

import java.text.CollationKey;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.internal.http.HttpMethod;

/**
 * Create By Visen
 * Date: 2021/8/23
 */
public class HttpUtil {
    // 测试对象： useracc1 , 1213212
    public static String ADDRESS = "http://47.108.249.115:8080/LuShuDao0.0.2-1.0-SNAPSHOT/";
    public static String EMAIL_ADDRESS = "http://47.108.249.115:8080/ShuDao0.0.2-1.0-SNAPSHOT";
    public static String FILE_ADDRESS = "http://47.108.249.115:8080/ShuDao_oss0.0.1-1.0-SNAPSHOT/";
    public static String COOKIE = ""; // cookie
    public static List<Cookie> cookieList = new ArrayList<Cookie>();
    public static OkHttpClient newOkHttpClient = new OkHttpClient();
    public static OkHttpClient okHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
        @Override
        public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
            cookieList = list;
            COOKIE = "JSESSIONID=" + list.get(0).value();
        }

        @NotNull
        @Override
        public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
            System.out.println("执行: cookieList: "+cookieList);
            return cookieList;
        }
    }).build();

    public static void getPostResponse(String url , FormBody formBody ,Callback callback){
        Request request = new Request.Builder().url(url).post(formBody).build();
//        System.out.println("size "+request.headers().size());
//        System.out.println(request.header("Cookie"));
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }

    public static void getPostResponseWithResuqestBody(String url , RequestBody requestBody ,Callback callback){
        Request request = new Request.Builder().url(url).post(requestBody).addHeader("Cookie", HttpUtil.COOKIE+" path=/ShuDao0.0.2-1.0-SNAPSHOT; httponly").addHeader("Content-Type","application/json;").build();
        System.out.println(request.toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }

    public static void getGetResponse(String url,Callback callback){
        Request request = new Request.Builder().url(url).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }

    public static void getNewPost(String url,FormBody formBody,Callback callback){
        Request request = new Request.Builder().url(url).post(formBody).build();
        Call call = newOkHttpClient.newCall(request);
        call.enqueue(callback);
    }

}
